/**
 * Copyright (c) 2019 Coder League
 * All rights reserved.
 *
 * File：GoodsMgrService.java
 * History:
 *         2019年5月18日: Initially created, wangjb.
 */
package club.coderleague.ilsp.service.good;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import club.coderleague.data.jpa.domain.Page;
import club.coderleague.ilsp.common.config.properties.FileUploadSettings;
import club.coderleague.ilsp.common.domain.beans.AttachBean;
import club.coderleague.ilsp.common.domain.beans.GoodsExtension;
import club.coderleague.ilsp.common.domain.beans.GoodsSettleExtension;
import club.coderleague.ilsp.common.domain.beans.UploadFile;
import club.coderleague.ilsp.common.domain.enums.EntityState;
import club.coderleague.ilsp.common.util.RichTextEditorUtil;
import club.coderleague.ilsp.controller.goods.bean.GoodSpecsBean;
import club.coderleague.ilsp.controller.goods.bean.SaveGoodsBean;
import club.coderleague.ilsp.dao.GoodPhotosMgrDao;
import club.coderleague.ilsp.dao.GoodSalesDao;
import club.coderleague.ilsp.dao.GoodSpecsDao;
import club.coderleague.ilsp.dao.GoodsMgrDao;
import club.coderleague.ilsp.dao.MerchantSettlesDao;
import club.coderleague.ilsp.entities.Goodphotos;
import club.coderleague.ilsp.entities.Goods;
import club.coderleague.ilsp.entities.Goodsales;
import club.coderleague.ilsp.entities.Goodspecs;
import club.coderleague.ilsp.entities.Merchantsettles;

/**
 * 商品管理业务处理异常。
 * @author wangjb
 */
@Service
public class GoodsMgrService {
	
	/**
	 * 商品管理数据访问对象。 
	 */
	@Autowired GoodsMgrDao goodDao;
	
	/**
	 * 商品相册管理数据访问对象。
	 */
	@Autowired GoodPhotosMgrDao goodPhotosDao;
	
	/**
	 * 商品规格数据访问对象。
	 */
	@Autowired GoodSpecsDao GSD;

	/**
	 * 商品销售表。
	 */
	@Autowired GoodSalesDao goodSalesDao;
	
	/**
	 * 删除入驻。
	 */
	@Autowired MerchantSettlesDao MSD;
	
	/**
	 * 附件配置表。
	 */
	@Autowired FileUploadSettings upload;
	
	/**
	 * 富文本编辑器。
	 */
	@Autowired RichTextEditorUtil richTextEditorUtil;

	/**
	 * 获取商品分页数据。
	 * @author wangjb 2019年5月18日。
	 * @param params 关键字查询参数。
	 * @return
	 */
	public Page<GoodsExtension> getGoodsMgrService(Map<String, Object> params)  throws Exception{
		Page<GoodsExtension> result = this.goodDao.getGoodsMgrDao(params);
		return result;
	}

	/**
	 * 根据商品id获取商品对象。
	 * @author wangjb 2019年5月18日。
	 * @param entityid 商品id。
	 * @return
	 */
	public Map<String, Object> getGoodsObjByEntityidService(Long entityid) {
		Map<String, Object> result = new HashMap<String, Object>();
		Goods goods = this.goodDao.getOne(entityid);
		goods.setGooddesc(this.richTextEditorUtil.replaceVisitImgPathUtil(goods.getGooddesc()));
		result.put("goods", goods);
		List<Map<String, Object>> goodsalebean = this.GSD.getGoodSpecsByGoodIdDao(entityid);
		result.put("goodsalebean", goodsalebean);
		List<AttachBean> goodPhoto = new ArrayList<AttachBean>();
		List<AttachBean> coverPhoto = new ArrayList<AttachBean>();
		List<Goodphotos> photoList = this.goodPhotosDao.getGoodPhotoListByGoodidDao(entityid, true);
		AttachBean ab = null;
		for (Goodphotos photo : photoList) {
			ab = new AttachBean(String.valueOf(photo.getEntityid()), photo.getPhotopath().substring(photo.getPhotopath().lastIndexOf("/") + 1, photo.getPhotopath().length()), 
					upload.getGoodPhotosPath() + photo.getPhotopath());
			if (photo.getCoverphoto()) coverPhoto.add(ab);
			else  goodPhoto.add(ab);
		}
		result.put("goodPhoto", goodPhoto);
		result.put("coverPhoto", coverPhoto);
		return result;
	}

	/**
	 * 获取商户标识。
	 * @author wangjb 2019年5月18日。
	 * @return
	 */
	public List<GoodsSettleExtension> getMerchantIdListService() {
		List<GoodsSettleExtension> result = this.goodDao.getMerchantIdListDao();
		return result;
	}

	/**
	 * 获取商品分类标识。
	 * @author wangjb 2019年5月18日。
	 * @return
	 */
	public List<Map<String, Object>> getGroupIdListService() {
		List<Map<String, Object>> result = this.goodDao.getGroupIdListDao();
		return result;
	}

	/**
	 * 新增编辑商品对象。
	 * @author wangjb 2019年5月18日。
	 * @param result 返回结果操作。
	 * @param objBean 表单数据。
	 */
	public void updateGoodsObjService(Map<String, Object> result, SaveGoodsBean goodsBean) {
		Goods goods = goodsBean.getGoods();
		Boolean repeat = this.goodDao.getRepeatBySettleIdAndGroupIdAndGoodNameDao(goods.getMerchantid(), goods.getGroupid(), goods.getGoodname(), goods.getEntityid());
		if (repeat) {
			result.put("state", false);
			result.put("msg", "已存在重复的名称!");
			return;
		}
		// 替换路径。
		goods.setGooddesc(this.richTextEditorUtil.replaceDepositLibPathUtil(goods.getGooddesc()));
		this.goodDao.save(goods);
		Long goodid = goods.getEntityid();
		
		Goodspecs obj = null;
		for (GoodSpecsBean person : goodsBean.getGoodSpecsBean()) {
			String[] entityid = person.getEntityid().split("_");
			obj = new Goodspecs();
			if (entityid.length > 1 && ("add").equals(entityid[0]) && ("del").equals(entityid[1])) continue;
			if (("add").equals(entityid[0])) { // 新增。
				Boolean specRepeat = this.GSD.getSpecRepeatByGoodIdAndSpecDefineDao(goodid, person.getSpecdefine(), null);
				if (specRepeat) {
					result.put("state", false);
					result.put("msg", "已存在重复的规格!");
					return;
				}
				Goodspecs spec = this.GSD.getGoodSpecsByGoodIdAndSpecDefineDao(goodid, person.getSpecdefine());
				if (spec != null) {
					spec.setEntitystate(EntityState.VALID.getValue());
					spec.setMeterunit(person.getMeterunit());
					continue;
				}
				obj.setEntitystate(EntityState.VALID.getValue());
				obj.setGoodid(goodid);
				obj.setSpecdefine(person.getSpecdefine());
				obj.setMeterunit(person.getMeterunit());
				this.GSD.save(obj);
			} else if (entityid.length == 1 && !("add").equals(entityid[0])) { //修改。
				Boolean specRepeat = this.GSD.getSpecRepeatByGoodIdAndSpecDefineDao(goodid, person.getSpecdefine(), Long.valueOf(entityid[0]));
				if (specRepeat) {
					result.put("state", false);
					result.put("msg", "已存在重复的规格!");
					return;
				}
				Goodspecs libObj = this.GSD.getOne(Long.valueOf(entityid[0]));
				libObj.setSpecdefine(person.getSpecdefine());
				libObj.setMeterunit(person.getMeterunit());
			} else if (entityid.length > 1 && !("add").equals(entityid[0]) && ("del").equals(entityid[1])) { // 删除。
//				Boolean exist = this.goodDao.getPutawayGoodBygoodidDao(goods.getEntityid()); // 废弃。
//				if (exist) {
//					result.put("state", false);
//					result.put("msg", "该商品规格【" + person.getSpecdefine() + "】已关联销售数据,不能进行删除操作!");
//					return;
//				}
				Goodspecs libObj = this.GSD.getOne(Long.valueOf(entityid[1]));
				libObj.setEntitystate(EntityState.INVALID.getValue());
				this.updateGoodSalesEntitystate(libObj.getEntityid(), false);
			}
		}
		
//		List<Goodphotos> photoList = this.goodPhotosDao.getGoodPhotoListByGoodidDao(goodid); // 查询商品是否有封面。
//		boolean flag = false;
		Goodphotos photoObj = null;
		List<Goodphotos> photoInsertList = new ArrayList<Goodphotos>();
		for (UploadFile file : goodsBean.getGoodphoto()) { // 普通相册。
			photoObj = new Goodphotos();
			photoObj.setEntitystate(EntityState.VALID.getValue());
			photoObj.setGoodid(goodid);
			photoObj.setPhotopath(file.getSavePath());
			photoObj.setCoverphoto(false);
			photoInsertList.add(photoObj);
		}
		
		for (UploadFile file : goodsBean.getCoverphoto()) { // 普通相册。
			photoObj = new Goodphotos();
			photoObj.setEntitystate(EntityState.VALID.getValue());
			photoObj.setGoodid(goodid);
			photoObj.setPhotopath(file.getSavePath());
			photoObj.setCoverphoto(true);
			photoInsertList.add(photoObj);
		}
		
		this.goodPhotosDao.saveAll(photoInsertList);
		
		if (!"".equals(goodsBean.getDel())) {
			String[] ids = goodsBean.getDel().split(",");
			for (String id : ids) {
				Goodphotos gp = this.goodPhotosDao.getOne(Long.valueOf(id));
				gp.setEntitystate(EntityState.INVALID.getValue());
			}
		}
		result.put("state", true);
		result.put("msg", "操作成功!");
	}

	/**
	 * 根据商品id修改商品状态。
	 * @author wangjb 2019年5月19日。
	 * @param entityid 商品id。
	 * @param entitystate 商品状态。
	 */
	public void updateEntitystateByGoodIdService(String entityid, Integer entitystate, Map<String, Object> result) {
		for (String id : entityid.split(",")) {
			Goods goods = this.goodDao.getOne(Long.parseLong(id));
			if (entitystate == EntityState.VALID.getValue()) {
				Boolean repeat = this.goodDao.getRepeatBySettleIdAndGroupIdAndGoodNameDao(goods.getMerchantid(), goods.getGroupid(), goods.getGoodname(), goods.getEntityid());
				if (repeat) {
					result.put("state", false);
					result.put("msg", "已存在重复的名称!");
					return;
				}
				List<Goodspecs> goodSpecsList = this.GSD.findByGoodid(goods.getEntityid()); // 查询商品规格数据级联删除。
				for (Goodspecs goodspecs : goodSpecsList) {
					if (EntityState.CASCADEDELETED.equalsValue(goodspecs.getEntitystate())) { // 恢复级联删除。
						goodspecs.setEntitystate(EntityState.CASCADEDELETED.getValue());
						this.updateGoodSalesEntitystate(goodspecs.getEntityid(), true);
					}
				}
			} else if (entitystate == EntityState.INVALID.getValue()) { // 删除到回收站，检查是否有上架的商品。
//				Boolean repeat = this.goodDao.getPutawayGoodBygoodidDao(goods.getEntityid()); // 废弃。
//				if (repeat) {
//					result.put("state", false);
//					result.put("msg", "该商品已关联销售数据,不能进行删除操作!");
//					return;
//				}
				List<Goodspecs> goodSpecsList = this.GSD.findByGoodid(goods.getEntityid()); // 查询商品规格数据级联删除。
				for (Goodspecs goodspecs : goodSpecsList) {
					goodspecs.setEntitystate(EntityState.CASCADEDELETED.getValue());
					this.updateGoodSalesEntitystate(goodspecs.getEntityid(), false);
				}
				
			}
		    goods.setEntitystate(entitystate);
		}
		result.put("state", true);
		result.put("msg", "操作成功!");
	}

	/**
	 * 根据商品id获取商品详情。
	 * @author wangjb 2019年5月19日。
	 * @param entityid 商品id。
	 * @return
	 */
	public Map<String, Object> getGoodsDetailByEntityidService(Long entityid) {
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> goods = this.goodDao.getGoodsDetailByEntityidDao(entityid);
		result.put("goods", goods);
		List<Map<String, Object>> goodsalebean = this.GSD.getGoodSpecsByGoodIdDao(entityid);
		result.put("goodsalebean", goodsalebean);
		List<AttachBean> goodPhoto = new ArrayList<AttachBean>();
		List<AttachBean> coverPhoto = new ArrayList<AttachBean>();
		List<Goodphotos> photoList = this.goodPhotosDao.getGoodPhotoListByGoodidDao(entityid, true);
		AttachBean ab = null;
		for (Goodphotos photo : photoList) {
			ab = new AttachBean("1", photo.getPhotopath().substring(photo.getPhotopath().lastIndexOf("/") + 1, photo.getPhotopath().length()), 
					upload.getGoodPhotosPath() + photo.getPhotopath());
			if (photo.getCoverphoto()) coverPhoto.add(ab);
			else  goodPhoto.add(ab);
		}
		result.put("goodPhoto", goodPhoto);
		result.put("coverPhoto", coverPhoto);
		return result;
	}

	/**
	 * 根据商品id查询商品的详情。
	 * @author wangjb 2019年7月25日。
	 * @param entityid 商品id。
	 * @return
	 */
	public String getGraphicDetailByIdService(Long entityid) {
		Goods good = this.goodDao.getOne(entityid);
		return this.richTextEditorUtil.replaceVisitImgPathUtil(good.getGooddesc());
	}
	
	/**
	 * 修改商品销售值。
	 * @author wangjb 2019年7月30日。
	 * @param specid 规格id。
	 * @param flag T、恢复，F、删除。
	 */
	public void updateGoodSalesEntitystate(Long specid, boolean flag) {
		List<Goodsales> saleList = this.goodSalesDao.findBySpecid(specid);
		for (Goodsales goodSales : saleList) {
			if (flag) {
				Merchantsettles ms = this.MSD.getOne(goodSales.getSettleid());
				if (EntityState.VALID.equalsValue(ms.getEntitystate()) && EntityState.CASCADEDELETED.equalsValue(goodSales.getEntitystate())) {
					goodSales.setEntitystate(goodSales.getOriginalstate()); 
				}
				continue;
			}
			if (EntityState.VALID.equalsValue(goodSales.getEntitystate()) || EntityState.PUBLISHED.equalsValue(goodSales.getEntitystate())) { // 上架和有效。
				goodSales.setOriginalstate(goodSales.getEntitystate()); // 记录原始值。
				goodSales.setEntitystate(EntityState.CASCADEDELETED.getValue()); // 修改为级联删除。
			}
		}
	}

}
